import time
import socket
from threading import Timer

import redis
import requests


def read_data(filepath):
    # try:
    with open(filepath, "r") as f:
        lines = f.readlines()
        return lines
    # except Exception as e:
    #     print(str(e))


def add_ip(filepath, ip):
    with open(filepath, "r") as f:
        lines = f.readlines()
    for line in lines:
        if ip in line:
            return
    add_line(filepath, ip)


def add_line(filepath, line):
    with open(filepath, 'a') as f:
        f.write(line + "\n")


def delete_ip(filepath, ip):
    with open(filepath, "r") as f:
        lines = f.readlines()
    with open(filepath, "w") as f_w:
        if lines:
            for line in lines:
                if ip in line:
                    continue
                f_w.write(line)


def get_ms_time():
    t = time.time()
    return str(round(t * 1000))


def get_network_ip():
    """get the local network ip, not loopback 127.*"""
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('1.1.1.1', 80))
    ip = s.getsockname()[0]
    s.close()
    return ip


def collect_data(ip, o):
    url_ip = "http://" + ip + ":9090/api/v1/query?query="
    url = url_ip + o
    try:
        results = requests.get(url)
        rs = results.json()
        return rs
    except Exception as e:
        print(e)
        return None


def send_to_redis_one(ip, msg, topic):
    # try:
    rdb = redis.Redis(host=ip, port=6379, db=1, decode_responses=True)
    rdb.rpush(topic, msg)
    rdb.close()
    # except Exception as e:
    #     print(str(e))


def send_to_redis_ones(ip, msgs, topic):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=1, decode_responses=True)
        for msg in msgs:
            rdb.rpush(topic, msg)
        rdb.close()
    except Exception as e:
        print(str(e))


def get_from_redis(ip, topic):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=1, decode_responses=True)
        msgs = []
        while rdb.llen(topic) != 0:
            msgs.append(rdb.rpop(topic))
        rdb.close()
        return msgs
    except Exception as e:
        print(str(e))


def set_redis_2(ip, msg, topic, ex=0):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=2, decode_responses=True)
        if ex == 0:
            rdb.set(topic, msg)
        else:
            if rdb.get(topic) is not None:
                rdb.expire(topic, ex)
            else:
                rdb.set(topic, msg, ex=ex)
        rdb.close()
    except Exception as e:
        print(str(e))


def check_redis_2(ip):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=2, decode_responses=True)
        lines = rdb.keys()
        rdb.close()
        return lines
    except Exception as e:
        print(e)


def set_redis(ip, msg, topic, ex=0):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=1, decode_responses=True)
        if ex == 0:
            pass
        else:
            if rdb.get(topic) is not None:
                rdb.expire(topic, ex)
            else:
                rdb.set(topic, msg, ex=ex)
        rdb.close()
    except Exception as e:
        print(e)


def check_redis(ip, topic):
    try:
        rdb = redis.Redis(host=ip, port=6379, db=1, decode_responses=True)
        lines = rdb.keys()
        rdb.close()
        if topic in lines:
            return True
        else:
            return False
    except Exception as e:
        print(e)


class RepeatingTimer(Timer):
    def run(self):
        while not self.finished.is_set():
            self.function(*self.args, **self.kwargs)
            self.finished.wait(self.interval)
